package database

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "os"
    "xorm.io/xorm"
    "xorm.io/xorm/log"
)

var DB *DataBase

type DataBase struct {
    MySQL     *xorm.Engine
    SQLServer *xorm.Engine
    InfluxDB  *xorm.Engine
}

func init() {

    // 数据库环境变量(构建时删除)
    os.Setenv("DB_HOST", "172.16.15.6")
    os.Setenv("DB_PORT", "3306")
    os.Setenv("DB_USER", "root")
    os.Setenv("DB_PASSWORD", "rd123456")
    os.Setenv("DB_NAME", "cloud_dev_tools")
    os.Setenv("DB_CHARSET", "utf8")
    os.Setenv("DB_LOG_LEVEL", "DEBUG")

    // 拼接数据库地址
    // "root:rd123456@tcp(172.16.15.6:3306)/cloud_dev_tools?charset=utf8"
    dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s",
        os.Getenv("DB_USER"),
        os.Getenv("DB_PASSWORD"),
        os.Getenv("DB_HOST"),
        os.Getenv("DB_PORT"),
        os.Getenv("DB_NAME"),
        os.Getenv("DB_CHARSET"),
    )

    // 连接数据库
    mysql, err := xorm.NewEngine("mysql", dataSourceName)
    if err != nil {
        panic(err.Error())
    }
    // 控制台显示SQL(默认: false)
    mysql.ShowSQL(true)
    // 定义日志级别字符转换
    logLevel := getLogLevel()
    // 通过日志级别控制，控制台是否输出SQL文本
    mysql.SetLogLevel(logLevel[os.Getenv("DB_LOG_LEVEL")])
    // 初始化数据库对象
    DB = &DataBase{
        MySQL: mysql,
    }
}

func getLogLevel() map[string]log.LogLevel {
    logLevel := make(map[string]log.LogLevel)
    logLevel["DEBUG"] = log.LOG_DEBUG
    logLevel["INFO"] = log.LOG_INFO
    logLevel["WARNING"] = log.LOG_WARNING
    logLevel["ERR"] = log.LOG_ERR
    logLevel["OFF"] = log.LOG_OFF
    logLevel["UNKNOWN"] = log.LOG_UNKNOWN
    return logLevel
}
